package controller

import (
	"fmt"
	"github.com/go-pay/gopay"
	"ksd-social-api/commons/base/controller"
	utils2 "ksd-social-api/utils"
	"strconv"
)

type AlipayNativeNoteController struct {
	controller.BaseController
	AlipayPayBaseController
}

/**
 * 支付宝支付-课程
 * @author feige
 * @date 2023-12-04
 * @version 1.0
 * @desc
 */
func (web *AlipayNativeNoteController) NativePay() {
	client, ctx := web.GetAlipayPayClient()
	if nil == client {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	uvo := userService.GetUserById(web.GetUserId(), web.GetSystemId())
	if nil == uvo {
		web.FailCodeMsg(901, "没找到支付用户")
		return
	}

	// 课程业务
	noteId, _ := web.ParseParamUint64("opid")
	noteDetailPayVo, err := noteService.GetNoteByIDToPay(noteId, web.GetSystemId())
	if err != nil {
		web.FailCodeMsg(901, "支付的课程不存在！")
		return
	}

	// 参数map
	price, _ := strconv.ParseFloat(noteDetailPayVo.Price, 10)
	mattch := map[string]any{}
	mattch["userId"] = web.GetUserId()
	mattch["opid"] = noteId
	mattch["systemId"] = web.GetSystemId()
	mattch["type"] = "note"
	mattch["price"] = price

	OutTradeNo := web.GetSnowWorkerIdString(5)
	fmt.Println("阿里支付：OutTradeNo", OutTradeNo)
	//请求参数
	bm := make(gopay.BodyMap)
	bm.Set("subject", noteDetailPayVo.Title)
	bm.Set("out_trade_no", fmt.Sprintf("%s_%s_%d_%d", OutTradeNo, "note", web.GetUserId(), noteId))
	bm.Set("total_amount", noteDetailPayVo.Price)
	// 发起交易
	m := map[string]any{}
	// 阿里支付生成支付链接
	aliRsp, err := client.TradePrecreate(ctx, bm)
	if err != nil {
		// 处理错误
		m["url"] = ""
		m["status"] = "fail"
		m["tradeNo"] = ""
	} else {
		// 处理返回结果
		m["url"] = aliRsp.Response.QrCode
		m["tradeNo"] = aliRsp.Response.OutTradeNo
		m["status"] = "success"
	}

	web.Ok(m)
}

/**
 * 课程回调
 * @author feige
 * @date 2023-12-04
 * @version 1.0
 * @desc
 */
func (web *AlipayNativeNoteController) QueryOrderByOutTradeNo() {
	// 获取支付的交易编号
	OutTradeNo := web.GetString("tradeno")
	client, ctx := web.GetAlipayPayClient()
	if nil == client {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	//请求参数
	bm := make(gopay.BodyMap)
	bm.Set("out_trade_no", OutTradeNo)
	aliRsp, err := client.TradeQuery(ctx, bm)
	if err != nil {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	response := aliRsp.Response
	// TRADE_FINISHED
	tmp := make(map[string]interface{})
	if response.TradeStatus == "TRADE_SUCCESS" {
		noteId, _ := web.GetUint64("opid")
		isBuyFlag := userNoteService.CountUserBuyNote(web.GetUserId(), noteId, web.GetSystemId())
		if !isBuyFlag {
			web.FailCodeMsg(902, "用户已经购买此课程!")
			return
		}
		// 订单保存落库
		userNoteService.SaveUserNote(
			response.OutTradeNo, response.TradeNo, utils2.StructToJson(response), 2, "支付宝", response.TotalAmount,
			web.GetUserId(), noteId, web.GetSystemId(), web.GetSystemName())
		//支付宝支付回调返回特殊处理，Flag = 40
		tmp["code"] = "SUCCESS"
		tmp["message"] = "成功"
		web.Ok(tmp)
	} else {
		web.FailCodeMsg(901, "fail")
	}

}
